package com.daisuxia.task;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.daisuxia.back.utils.SysCacheUtils;
import com.daisuxia.web.pojo.BackConfigParams;
import com.daisuxia.web.pojo.BorrowOrder;
import com.daisuxia.web.pojo.Repayment;
import com.daisuxia.web.pojo.User;
import com.daisuxia.web.service.IBorrowOrderService;
import com.daisuxia.web.service.IRepaymentService;
import com.daisuxia.web.service.IUserService;
import com.daisuxia.zzc.DateUtils;
import com.daisuxia.zzc.ZzcRequest1;
import com.daisuxia.zzc.ZzcRequest2;
import com.daisuxia.zzc.ZzcResult;

import redis.clients.jedis.JedisCluster;

/**
 * 中智诚推送
 * @Description:
 */

public class ZzcPushTaskService {
	
	private static Logger logger = LoggerFactory.getLogger(ZzcPushTaskService.class);
	@Autowired
	JedisCluster jedisCluster;
	@Autowired
	private IBorrowOrderService borrowOrderService;
	@Autowired
	public IUserService userService;
	@Autowired
	public IRepaymentService repaymentService;
	/**
	 * 调用中智诚接口推送数据
	 *  贷款批核上报
	 * @throws ParseException 
	 */
	public void zzcPushIssue(){
			//每日从数据库拿到数据 满足两个条件订单状态为已放款/待还款 ，审核日期为当前时间的前一个工作日
			Date conditionTime=DateUtils.addDay(new Date(), -1);
			String zzcReportTime=DateUtils.formatDate(conditionTime, "yyyy-MM-dd");
		    HashMap<String,Object> params=new HashMap<String,Object>();
		    params.put("borrowStatus", 21);
		    params.put("zzcReportTime", zzcReportTime);
			List<BorrowOrder> orderList=borrowOrderService.findAll(params);
			
		    LinkedHashMap<String, String> map2 = SysCacheUtils.getConfigParams(BackConfigParams.ZZC);
			String url = map2.get("ZZC_URL_ISSUE");
			String name = map2.get("ZZC_NAME");
			String pwd = map2.get("ZZC_PWD");
			for (BorrowOrder borrowOrder : orderList) {
				ZzcRequest1  zzcRequest=new ZzcRequest1();
		 		zzcRequest.setName(borrowOrder.getRealname());
		 		zzcRequest.setPid(borrowOrder.getIdNumber());
		 		zzcRequest.setMobile(borrowOrder.getUserPhone());
		 		zzcRequest.setLoanId(borrowOrder.getId()+"");
		 		zzcRequest.setLoanAmount(borrowOrder.getMoneyAmount());
		 		User user = userService.searchByUserid(borrowOrder.getUserId());
		 		if(user!=null && user.getCreateTime()!=null) {
		 			zzcRequest.setAccountOpenDate(user.getCreateTime());
		 		}
		 		zzcRequest.setApplyDate(borrowOrder.getOrderTime());
		 		zzcRequest.setIssueDate(borrowOrder.getLoanTime());
		 		zzcRequest.setLoanType("1");
		 		zzcRequest.setTotalTerm(1);
		 		zzcRequest.setTermPeriod(14);
		 		zzcRequest.setFirstRepaymentDate(DateUtils.addDay(borrowOrder.getLoanTime(), 14));
					//通过工具类提交数据
					 HttpClient c = new HttpClient();
					 try {
				    	 String jsonStrData =JSON.toJSONString(zzcRequest);
				    	 logger.info("zzc上报json数据：  "+jsonStrData);
				         c.getParams().setContentCharset("utf-8");
				         c.getParams().setAuthenticationPreemptive(true);
				         Credentials defaultcreds = new UsernamePasswordCredentials(name, pwd);
				         c.getState().setCredentials(AuthScope.ANY, defaultcreds);
				         PostMethod getMethod = new PostMethod(url);
				         getMethod.setRequestHeader("Content-type", "application/json");
				         getMethod.setRequestBody(jsonStrData);
						 c.executeMethod(getMethod);
						 String rs = getMethod.getResponseBodyAsString();
						 ZzcResult res=JSON.parseObject(rs, new TypeReference<ZzcResult>() {});
						 if(res!=null && res.getStatus()==null) {
				        	 continue;
				         }
				         if(res!=null && res.getStatus().equals("success")) {
				        	 logger.info("接口一上报数据成功！");
				         }
					} catch (Exception e1) {
						logger.error(e1.getMessage());
					}
				
			}
	}
	/**
	 * 调用中智诚接口推送数据
	 *  借贷人账户状态变动更新
	 */
	public void zzcPushTrack() {
	   
	    	Date startTime=DateUtils.addDay(new Date(), -15);
			Date endTime=DateUtils.addDay(new Date(), 15);
	        String startTime1=DateUtils.formatDate(startTime, "yyyy-MM-dd");
	        String endTime1=DateUtils.formatDate(endTime, "yyyy-MM-dd");
		    HashMap<String,Object> params=new HashMap<String,Object>();
		    int[] statuses=null;
		    if(null == statuses || statuses.length == 0){
				// 还款状态为-11 23 30 34  23:部分还款;30:已还款;-11:已逾期;34逾期已还款;
				statuses = new int[]{-11,23,30,34};
			}
		    params.put("statuses", statuses);
		    params.put("repaymentTimeStart", startTime1);
		    params.put("repaymentTimeEnd", endTime1);
			 List<Repayment> repaymentList=repaymentService.findAll2(params);
			 LinkedHashMap<String, String> map2 = SysCacheUtils.getConfigParams(BackConfigParams.ZZC);
			 String url = map2.get("ZZC_URL_TRACK");
			 String name = map2.get("ZZC_NAME");
			 String pwd = map2.get("ZZC_PWD");
			 for (Repayment repayment : repaymentList) {
				//组装数据
				ZzcRequest2  zzcRequest=new ZzcRequest2();
		        zzcRequest.setLoanId(repayment.getAssetOrderId()+"");
		 		zzcRequest.setName(repayment.getRealname());
		 		User user = userService.searchByUserid(repayment.getUserId());
		 		if(user!=null && user.getIdNumber()!=null) {
		 			zzcRequest.setPid(user.getIdNumber());
		 			zzcRequest.setMobile(user.getUserPhone());
		 		}
		 		zzcRequest.setTermNo(1);
		 		if(repayment.getStatus()==30 || repayment.getStatus()==34) {
		 			zzcRequest.setTermStatus("normal");
		 			zzcRequest.setOverdueStatus("");
		 		}
		 		if(repayment.getStatus()==-11 || repayment.getStatus()==23) {
		 			zzcRequest.setTermStatus("overdue");
		 			zzcRequest.setOverdueStatus("M1");
		 		}
		 		zzcRequest.setTargetRepaymentDate(repayment.getRepaymentTime());
		 		zzcRequest.setRealRepaymentDate(repayment.getRepaymentRealTime());
		 		zzcRequest.setTargetRepayment(new BigDecimal(repayment.getRepaymentAmount()).divide(new BigDecimal(100)));
		 		zzcRequest.setRealRepayment(new BigDecimal(repayment.getRepaymentedAmount()).divide(new BigDecimal(100)));
		 		zzcRequest.setStatusConfirmAt(new Date());
		 		//通过工具类提交数据
		 		 HttpClient c = new HttpClient();
		    	 String jsonStrData =JSON.toJSONString(zzcRequest);
		    	 logger.info("借贷人账户状态变动更新：  "+jsonStrData);
		         c.getParams().setContentCharset("utf-8");
		         c.getParams().setAuthenticationPreemptive(true);
		         Credentials defaultcreds = new UsernamePasswordCredentials(name, pwd);
		         c.getState().setCredentials(AuthScope.ANY, defaultcreds);
		         
		         PostMethod getMethod = new PostMethod(url);
		         getMethod.setRequestHeader("Content-type", "application/json");
		         getMethod.setRequestBody(jsonStrData);
		         try {
					 c.executeMethod(getMethod);
					 String rs = getMethod.getResponseBodyAsString();
					 ZzcResult res=JSON.parseObject(rs, new TypeReference<ZzcResult>() {});
			         if(res!=null && res.getStatus()==null) {
			        	 continue;
			         }
			         if(res!=null && res.getStatus().equals("success")) {
			        	 logger.info("接口二上报数据成功！");
			         }
		         } catch (Exception e1) {
						logger.error(e1.getMessage());
				 }
			}
	}
	
}